var express = require('express');
var router = express.Router();
var db = require('../db');
var moment = require('moment');
const random = require('string-random');
let rpcMethods = [];

function register(name, fn, ns = "/"){
    rpcMethods[name] = fn;
}

function runMethod(message, ws) {
    if (!rpcMethods[message.method]){
        return {
            jsonrpc: "2.0",
            // error: utils.createError(-32601),
            error: -32601,
            id: message.id || null
        }
    }
    let response = rpcMethods[message.method](message.params, ws)
    return {
        jsonrpc: "2.0",
        result: response,
        id: message.id
    }
}

router.ws('/', function(ws, req) {
    let id = req.headers['sec-websocket-key'];
    let token = req.query.token
    console.log('socket id', id, token);
    db.query('select * from user where token = ?', [token], (error, result) => {
        if(error) throw error
        if(result.length > 0){
            ws.id = id;
            ws.on('message', function(msg) {
                let message = JSON.parse(msg)
                let response = rpcMethods[message.method](message, ws)
                console.log('onmessage', message, response)
                ws.send(JSON.stringify(response))
            });
        }else{
            ws.terminate(); //强制关闭连接
        }
    })
});

register('game.create', (params, ws) => {
    return ws.id;
})

module.exports = router;
